<?php

namespace app\api\controller;

use app\Request;
use think\facade\Db;
use PhpOffice\PhpWord\IOFactory;
use PhpOffice\PhpWord\Shared\Converter;
use PhpOffice\PhpWord\PhpWord;
use PhpOffice\PhpWord\Style\Font;
use PhpOffice\PhpWord\SimpleType\Jc;
use PhpOffice\PhpWord\SimpleType\TextAlignment;

//绩效考核报告
class Report
{
    public $monthRedData=[];
    public $lastMonthRedData=[];
    public $compareType="";
    public $compareCount="";
    public $compareContent="";
    public $phpWord;
    public $section;

    //报告导出
    public function export(Request $request)
    {
        $month=$request->param("month","2024-08-01");
        $yMonth=$request->param("lmonth","2024-07-01");
        //红色
        $this->monthRedData=$this->getData(3,$month);
        $this->lastMonthRedData=$this->getData(3,$yMonth);
        $this->red($month,$yMonth);
        //黄色
        $this->monthRedData=$this->getData(2,$month);
        $this->lastMonthRedData=$this->getData(2,$yMonth);
        $this->yellow($month,$yMonth);

        // 导出Word文件
        $filename = '分局绩效考评-'.$month.'.docx';
        $this->phpWord->save($filename, 'Word2007');

        // 下载导出的文件
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        readfile($filename);
        unlink($filename);


    }

    //status 3红色 2黄色
    public function getData($status=3,$fill_date="2024-08-01")
    {
        $allData=Db::table("pf_work")
            ->field("r.*,d.dept_name,w.fill_date,w.rank,w.basic")
            ->alias("w")
            ->join("work_results r","w.id = work_id")
            ->join("sys_dept d","w.org_id = d.dept_id")
            ->where("w.fill_date",$fill_date)
            ->where("r.item_status",$status)
            ->where("r.level","<",3)
            ->where("r.status",20)
            ->where("r.deleted",0)
            ->where("r.zzkh",0)
            ->select()->toArray();
        //去除有子集的一级

        foreach ($allData as $allKey=>$allD)
        {
            if($allD["level"]  == 1)
            {
                if($row=DB::table("work_results")->where("p_id",$allD["item_id"])->where("status",20)->where("deleted",0)->find())
                {

                    if($row["item_id"] !== 999999){
                        unset($allData[$allKey]);
                    }

                }
            }
        }
        return $allData;
    }

    //条线上个月的数据
    public function getDataRow($fill_date="2024-07-01",$item_id=0)
    {
        $rowData=Db::table("pf_work")
            ->field("r.*,d.dept_name,w.fill_date,w.rank,w.basic")
            ->alias("w")
            ->join("work_results r","w.id = work_id")
            ->join("sys_dept d","w.org_id = d.dept_id")
            ->where("w.fill_date",$fill_date)
            ->where("r.item_id",$item_id)
            ->where("r.zzkh",0)
            ->find();
        return $rowData;
    }

    //红色
    public function red($month,$yMonth)
    {
        $this->compareCount=abs(intval(count($this->monthRedData) - count($this->lastMonthRedData)));
        if(count($this->monthRedData) > count($this->lastMonthRedData)){
            $this->compareType="增加".$this->compareCount."项。";
        }elseif(count($this->monthRedData) == count($this->lastMonthRedData)){
            $this->compareType="无变化。";
        }else{
            $this->compareType="减少".$this->compareCount."项。";
        }
        $names = array_map(function ($object) {
            return $object["dept_name"];
        }, $this->monthRedData);

        $names2 = array_map(function ($object) {
            return $object["dept_name"];
        }, $this->lastMonthRedData);

        // 统计部门现在的数量
        $nameCounts = array_count_values($names);


        $nameCounts2 = array_count_values($names2);

        $redBm="目前位于红区的分别为";
        $num=0;
        foreach ($nameCounts as $key=>$value)
        {
            $num++;
            if($num == (count($nameCounts)))
            {
                $redBm.=$key.$value."项。";
            }else{
                $redBm.=$key.$value."项,";
            }

        }

        $table=[];
        $lampNew=[];
        $lampLess=[];
        foreach ($nameCounts as $gName=>&$gValue)
        {
            $table[$gName]["name"]=$gName;
            $table[$gName]["compare"]=0;
            foreach ($nameCounts2 as $gName2=>$gValue2)
            {
                if($gName2 == $gName)
                {
                    $table[$gName]["compare"]=$gValue - $gValue2;
                }

            }
            foreach ($this->monthRedData as $monthRedDataRow)
            {
                $lData=$this->getDataRow($yMonth,$monthRedDataRow["item_id"]);
                $monthRedDataRow["l_item_status"]=$lData?$lData["item_status"]:0;
                if($monthRedDataRow["dept_name"]==$gName){
                    $table[$gName]["data"][]=$monthRedDataRow;
                    if($monthRedDataRow["item_status"] !== $monthRedDataRow["l_item_status"]) $lampNew[]=$monthRedDataRow;
                }
            }
        }
        //本月新增
        $newId=array_diff(array_column($this->monthRedData,"item_id"),array_column($this->lastMonthRedData,"item_id"));
        $newWords=count($newId)? "新增".count($newId)."项红色指标，" :"无新增红色指标，";
        if($newId) $newWords.="分别为";
        foreach ($newId as $new)
        {
            foreach ($this->monthRedData as $monthRow)
            {
                if($monthRow["item_id"] == $new)
                {
                    $newWords.=$monthRow["dept_name"].$monthRow["name"]."(".$monthRow["score"]."分)".",";
                }

            }
        }
        if($lampNew)
        {
            $mjValue=[
                0=>"无",
                1=>"绿",
                2=>"黄",
                3=>"红",
                4=>"蓝",
            ];
            $newWords.="    灯色上升质态：";
            foreach ($lampNew as $lampNewValue)
            {

                $newWords.=$monthRow["dept_name"].$monthRow["name"]."(".$monthRow["score"]."分)".$mjValue[$lampNewValue["l_item_status"]]."转红".",";
            }
        }


        //本月减少
        $reduceId=array_diff(array_column($this->lastMonthRedData,"item_id"),array_column($this->monthRedData,"item_id"));
        $newWords.=count($reduceId)? "减少".count($reduceId)."项，" :"无减少，";
        if($reduceId) $newWords.="分别为";
        foreach ($reduceId as $reduce)
        {
            foreach ($this->lastMonthRedData as $monthRow)
            {
                if($monthRow["item_id"] == $reduce)
                {
                    $nData=$this->getDataRow($month,$monthRow["item_id"]);
                    $monthRow["n_item_status"]=$nData?$nData["item_status"]:0;
                    $lampLess[]=$monthRow;
                    $newWords.=$monthRow["dept_name"].$monthRow["name"]."(".$monthRow["score"]."分)".",";
                }

            }
        }

        if($lampLess)
        {
            $mjValue=[
                0=>"无",
                1=>"绿",
                2=>"黄",
                3=>"红",
                4=>"蓝",
            ];
            $newWords.="    灯色下降质态：";
            foreach ($lampLess as $lampLessValue)
            {
                $newWords.=$lampLessValue["dept_name"].$lampLessValue["name"]."(".$lampLessValue["score"]."分)"."红转".$mjValue[$lampLessValue["n_item_status"]].",";
            }
        }

        // 创建一个新的Word文档对象
        $this->phpWord = new PhpWord();

        // 添加一个段落，并设置样式
        $this->section = $this->phpWord->addSection();
        $this->section->addText('相城分局绩效考评阶段性质态分析', ['bold' => true, 'size' => 22,'alignment' => Jc::CENTER]);

        // 添加HTML内容
        $html = '<p style="text-align:center">办公室</p>';
        $html .= '<p>下面重点围绕红区、黄区项目进行质态通报：</p>';
        $html .= '<p>一、红区（'.count($this->monthRedData).'项）</p>';
        $html .= '<p>     本月，警种部门红区指标共'.count($this->monthRedData).'项，环比上月'.count($this->lastMonthRedData).'项，'.$this->compareType."其中，".$newWords.$redBm.'</p>';
//        echo $html;exit;

        $dom = new \DOMDocument();
        $dom->loadHTML('<?xml encoding="UTF-8">' . $html);
        $paragraphs = $dom->getElementsByTagName('p');
        foreach ($paragraphs as $paragraph) {
            $text = $paragraph->nodeValue;
            $this->section->addText($text, ['size' => 16]);
        }

        //表格
        $this->section->addText('表1  红区指标统计情况', [ 'size' => 16,'alignment' => Jc::CENTER]);
        // 设置表格的样式
        $styleTable = array(

            'borderSize' => 6,
            'borderColor' => '999999',
            'cellMargin' => 50,
            'alignment' => \PhpOffice\PhpWord\SimpleType\JcTable::CENTER
        );
        $styleCell = array('valign' => 'center','size' => 16);

        $tables = $this->section->addTable($styleTable);

        $tables->addRow();
        $tables->addCell(3000,$styleCell)->addText("序号");
        $tables->addCell(3000,$styleCell)->addText("部门名称");
        $tables->addCell(3000,$styleCell)->addText("红区指标数量");
        $tables->addCell(3000,$styleCell)->addText("环比");
        $tables->addCell(3000,$styleCell)->addText("指标内容");
        $tables->addCell(3000,$styleCell)->addText("分值");
        $tables->addCell(3000,$styleCell)->addText("质态变化");

        $xh=0;
        $xh_1=0;
        foreach ($table as $tableRows)
        {
            $styleCell = array('valign' => 'center','size' => 16);
            $hlNum=0;
            $xh_1++;
            foreach ($tableRows["data"] as $tableRow)
            {
                $xh++;
                $hlNum++;
                $tables->addRow();
                if(count($tableRows["data"]) > 1){
                    if($hlNum == 1)
                    {
                        $styleCell = array('vMerge' => 'restart', 'valign' => 'center'); //设置跨列
                        $tables->addCell(3000,$styleCell)->addText($xh_1);
                        $tables->addCell(3000,$styleCell)->addText($tableRows["name"]);
                        $tables->addCell(3000,$styleCell)->addText(count($tableRows["data"]));
                        $tables->addCell(3000,$styleCell)->addText($tableRows["compare"]);
                    }else{
                        $tables->addCell(3000,array('vMerge' => 'continue'))->addText(null);
                        $tables->addCell(3000,array('vMerge' => 'continue'))->addText(null);
                        $tables->addCell(3000,array('vMerge' => 'continue'))->addText(null);
                        $tables->addCell(3000,array('vMerge' => 'continue'))->addText(null);
                    }
                }else{
                    $tables->addCell(3000,$styleCell)->addText($xh_1);
                    $tables->addCell(3000,$styleCell)->addText($tableRows["name"]);
                    $tables->addCell(3000,$styleCell)->addText(count($tableRows["data"]));
                    $tables->addCell(3000,$styleCell)->addText($tableRows["compare"]);
                }
                $tables->addCell(3000,$styleCell)->addText($tableRow["name"]);
                $tables->addCell(3000,$styleCell)->addText($tableRow["score"]);
                if($tableRow["item_status"] == $tableRow["l_item_status"])
                {
                    $status="延续";
                }else{
                    $mjValue=[
                        0=>"无",
                        1=>"绿",
                        2=>"黄",
                        3=>"红",
                        4=>"蓝",
                    ];
                    $status=$mjValue[$tableRow["l_item_status"]]."转红";

                }
                $tables->addCell(3000)->addText($status);
            }
        }

        //讲述表格内容
        foreach ($table as $tableRows)
        {
            $text = "       ".$tableRows["name"].':'."红区".count($tableRows["data"])."项";
            if($tableRows["compare"] > 0 ) $text.="，环比上月增加".$tableRows["compare"]."项。";
            if($tableRows["compare"] == 0 ) $text.="。";
            if($tableRows["compare"] < 0 ) $text.="，环比上月减少".abs($tableRows["compare"])."项。";
            $paixu=0;
            foreach ($tableRows["data"] as $tableRow)
            {
                $type=[
                    10=>"达标项",
                    20=>"竞争项",
                ];
                $paixu++;
                $text.="(".$paixu.")".$tableRow["name"].",";
                $text.="为".$type[$tableRow["type"]]."考核。";
                $text.="质态情况：".$tableRow["ext_1"];

            }
            $this->section->addText($text, ['size' => 16]);
        }



    }

    //黄色
    public function yellow($month,$yMonth)
    {
        $this->compareCount=abs(intval(count($this->monthRedData) - count($this->lastMonthRedData)));
        if(count($this->monthRedData) > count($this->lastMonthRedData)){
            $this->compareType="增加".$this->compareCount."项。";
        }elseif(count($this->monthRedData) == count($this->lastMonthRedData)){
            $this->compareType="无变化。";
        }else{
            $this->compareType="减少".$this->compareCount."项。";
        }
        $names = array_map(function ($object) {
            return $object["dept_name"];
        }, $this->monthRedData);

        $names2 = array_map(function ($object) {
            return $object["dept_name"];
        }, $this->lastMonthRedData);

        // 统计部门现在的数量
        $nameCounts = array_count_values($names);

        $nameCounts2 = array_count_values($names2);

        $redBm="目前位于黄区的分别为";
        $num=0;
        foreach ($nameCounts as $key=>$value)
        {
            $num++;
            if($num == (count($nameCounts)))
            {
                $redBm.=$key.$value."项。";
            }else{
                $redBm.=$key.$value."项,";
            }

        }

        $table=[];
        $lampNew=[];
        $lampLess=[];
        foreach ($nameCounts as $gName=>&$gValue)
        {
            $table[$gName]["name"]=$gName;
            $table[$gName]["compare"]=0;
            foreach ($nameCounts2 as $gName2=>$gValue2)
            {
                if($gName2 == $gName)
                {
                    $table[$gName]["compare"]=$gValue - $gValue2;
                }

            }
            foreach ($this->monthRedData as $monthRedDataRow)
            {
                $lData=$this->getDataRow($yMonth,$monthRedDataRow["item_id"]);
                $monthRedDataRow["l_item_status"]=$lData?$lData["item_status"]:0;
                if($monthRedDataRow["dept_name"]==$gName){
                    $table[$gName]["data"][]=$monthRedDataRow;
                    if($monthRedDataRow["item_status"] !== $monthRedDataRow["l_item_status"]) $lampNew[]=$monthRedDataRow;
                }
            }
        }
        //本月新增
        $newId=array_diff(array_column($this->monthRedData,"item_id"),array_column($this->lastMonthRedData,"item_id"));
        $newWords=count($newId)? "新增".count($newId)."项黄色指标，" :"无新增黄色指标，";
        if($newId) $newWords.="分别为";
        foreach ($newId as $new)
        {
            foreach ($this->monthRedData as $monthRow)
            {
                if($monthRow["item_id"] == $new)
                {
                    $newWords.=$monthRow["dept_name"].$monthRow["name"].",";
                }

            }
        }

        if($lampNew)
        {
            $mjValue=[
                0=>"无",
                1=>"绿",
                2=>"黄",
                3=>"红",
                4=>"蓝",
            ];
            $newWords.="    灯色上升质态：";
            foreach ($lampNew as $lampNewValue)
            {

                $newWords.=$monthRow["dept_name"].$monthRow["name"]."(".$monthRow["score"]."分)".$mjValue[$lampNewValue["l_item_status"]]."转黄".",";
            }
        }

        //本月减少
        $reduceId=array_diff(array_column($this->lastMonthRedData,"item_id"),array_column($this->monthRedData,"item_id"));
        $newWords.=count($reduceId)? "减少".count($reduceId)."项，" :"无减少，";
        if($reduceId) $newWords.="分别为";
        foreach ($reduceId as $reduce)
        {
            foreach ($this->lastMonthRedData as $monthRow)
            {
                if($monthRow["item_id"] == $reduce)
                {
                    $nData=$this->getDataRow($month,$monthRow["item_id"]);
                    $monthRow["n_item_status"]=$nData?$nData["item_status"]:0;
                    $lampLess[]=$monthRow;
                    $newWords.=$monthRow["dept_name"].$monthRow["name"]."(".$monthRow["score"]."分)".",";
                }

            }
        }

        if($lampLess)
        {
            $mjValue=[
                0=>"无",
                1=>"绿",
                2=>"黄",
                3=>"红",
                4=>"蓝",
            ];
            $newWords.="    灯色下降质态：";
            foreach ($lampLess as $lampLessValue)
            {
                if($lampLessValue["n_item_status"] == 3) continue;
                $newWords.=$lampLessValue["dept_name"].$lampLessValue["name"]."(".$lampLessValue["score"]."分)"."黄转".$mjValue[$lampLessValue["n_item_status"]].",";
            }
        }

        $html = '<p>二、黄区（'.count($this->monthRedData).'项）</p>';
        $html .= '<p>      本月，黄区指标共'.count($this->monthRedData).'项，环比上月'.count($this->lastMonthRedData).'项，'.$this->compareType."其中，".$newWords.$redBm.'</p>';
//        echo $html;exit;

        $dom = new \DOMDocument();
        $dom->loadHTML('<?xml encoding="UTF-8">' . $html);
        $paragraphs = $dom->getElementsByTagName('p');
        foreach ($paragraphs as $paragraph) {
            $text = $paragraph->nodeValue;
            $this->section->addText($text, ['size' => 16]);
        }

        //表格
        $this->section->addText('表2  黄区指标统计情况', [ 'size' => 16,'alignment' => Jc::CENTER]);
        // 设置表格的样式
        $styleTable = array(

            'borderSize' => 6,
            'borderColor' => '999999',
            'cellMargin' => 50,
            'alignment' => \PhpOffice\PhpWord\SimpleType\JcTable::CENTER
        );
        $styleCell = array('valign' => 'center','size' => 16,);
        $tables = $this->section->addTable($styleTable);

        $tables->addRow();
        $tables->addCell(3000,$styleCell)->addText("序号");
        $tables->addCell(3000,$styleCell)->addText("部门名称");
        $tables->addCell(3000,$styleCell)->addText("红区指标数量");
        $tables->addCell(3000,$styleCell)->addText("指标内容");
        $tables->addCell(3000,$styleCell)->addText("分值");
        $tables->addCell(3000,$styleCell)->addText("质态变化");

        $xh=0;
        $xh_1=0;
        foreach ($table as $tableRows)
        {
            $styleCell = array('valign' => 'center','size' => 16);
            $hlNum=0;
            $xh_1++;
            foreach ($tableRows["data"] as $tableRow)
            {
                $xh++;
                $hlNum++;

                $tables->addRow();
                if(count($tableRows["data"]) > 1){
                    if($hlNum == 1)
                    {
                        $styleCell = array('vMerge' => 'restart', 'valign' => 'center'); //设置跨列
                        $tables->addCell(3000,$styleCell)->addText($xh_1);
                        $tables->addCell(3000,$styleCell)->addText($tableRows["name"]);
                        $tables->addCell(3000,$styleCell)->addText(count($tableRows["data"]));
                    }else{
                        $tables->addCell(3000,array('vMerge' => 'continue'))->addText(null);
                        $tables->addCell(3000,array('vMerge' => 'continue'))->addText(null);
                        $tables->addCell(3000,array('vMerge' => 'continue'))->addText(null);
                    }
                }else{
                    $tables->addCell(3000,$styleCell)->addText($xh_1);
                    $tables->addCell(3000,$styleCell)->addText($tableRows["name"]);
                    $tables->addCell(3000,$styleCell)->addText(count($tableRows["data"]));
                }
                $tables->addCell(3000,$styleCell)->addText($tableRow["name"]);
                $tables->addCell(3000,$styleCell)->addText($tableRow["score"]);
                if($tableRow["item_status"] == $tableRow["l_item_status"])
                {
                    $status="延续";
                }else{
                    $mjValue=[
                        0=>"无",
                        1=>"绿",
                        2=>"黄",
                        3=>"红",
                        4=>"蓝",
                    ];
                    $status=$mjValue[$tableRow["l_item_status"]]."转黄";

                }
                $tables->addCell(3000)->addText($status);
            }
        }



        //讲述表格内容
        foreach ($table as $tableRows)
        {
            $text = "       ".$tableRows["name"].':'."红区".count($tableRows["data"])."项";
            if($tableRows["compare"] > 0 ) $text.="，环比上月增加".$tableRows["compare"]."项。";
            if($tableRows["compare"] == 0 ) $text.="。";
            if($tableRows["compare"] < 0 ) $text.="，环比上月减少".abs($tableRows["compare"])."项。";
            $paixu=0;
            foreach ($tableRows["data"] as $tableRow)
            {
                $type=[
                    10=>"达标项",
                    20=>"竞争项",
                ];
                $paixu++;
                $text.="(".$paixu.")".$tableRow["name"].",";
                $text.="为".$type[$tableRow["type"]]."考核。";
                $text.="质态情况：".$tableRow["ext_1"];

            }
            $this->section->addText($text, ['size' => 16]);
        }



    }


}